package com.aipp.mall.common.handler;

import com.aipp.mall.common.exception.ServerException;
import com.aipp.mall.common.redis.TokenService;
import com.aipp.mall.common.utils.IpUtils;
import com.aipp.mall.common.utils.LocalDataUtil;
import com.aipp.mall.h5.domain.entity.Member;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.date.DateUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author cc
 */
@Slf4j
@Component
public class H5MemberInterceptor implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 获取会员信息
        Member member = tokenService.getMember(request);
        if (member == null) {
            throw new ServerException(401, "请先登录");
        }
        // 将会员信息存放至全局
        LocalDataUtil.setVar(member);
        String requestUrl = request.getRequestURI();
        String ipAddr = IpUtils.getIpAddr(request);
        log.info("【请求：】用户Id:{} | ip:{} | 请求接口:{} | 请求时间:{} ", member.getId(), ipAddr, requestUrl, DateUtil.formatNow());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocalDataUtil.remove();
    }
}
